<template>
  <div class="wrapper">
    <div class="avatar" v-if="path||loading">
      <el-progress v-if="loading" :percentage="percentage" class="c-progress" :show-text="false"></el-progress>
      <el-image v-if="path" :src="filePath + path"></el-image>
    </div>
    <el-upload
      v-else
      class="avatar-uploader"
      drag
      :multiple="false"
      :action="actionUrl"
      :headers="headers"
      :on-success="onSuccess"
      :before-upload="onBeforeUpload"
      :show-file-list="false"
      :on-change="handleOnChange"
      :on-progress="onProgress"
      :disabled="loading"
    >
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
export default {
  name: "CAvaterUpload",
  props: {
    path: {
      type: String,
      default: "",
    },
    actionUrl: {
      type: String,
      default: "",
    },
    beforeUpload: {
      type: Function,
      default: () => {},
    },
  },
  computed: {
    headers() {
      let token = getToken();
      return token ? { Authorization: token } : {};
    },
  },
  data() {
    return {
      filePath,
      loading: false,
      percentage: 0,
    };
  },
  methods: {
    onSuccess(res, file, fileList) {
      this.$emit("uploadSuccess", res, file, fileList);
    },
    onBeforeUpload(file) {
      console.log(file);
      const valid = this.beforeUpload(file);
      if (valid === false) {
        this.loading = false;
        this.percentage = 0;
        return false;
      }
    },
    onRemove() {
      this.$emit("remove");
    },
    handleOnChange(file, fileList) {
      this.loading = true;
      if (file.percentage == 100) {
        this.loading = false;
        this.percentage = 0;
      }
    },
    onProgress(file) {
      this.percentage = file.percent;
    },
  },
};
</script>
<style lang="scss" scoped>
.wrapper{
  --img-width: 80px;
}
.avatar-uploader {
  ::v-deep .el-upload-dragger {
    width: var(--img-width);
    height: var(--img-width);
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: var(--img-width);
  height: var(--img-width);
  line-height: var(--img-width);
  text-align: center;
}
.avatar {
  width: var(--img-width);
  height: var(--img-width);
  display: block;
  position: relative;
}
.c-progress {
  width: 60px;
  height: 20px;
  left: 50%;
  top: 50%;
  transform: translate(-50%);
}
.w-200 {
  width: 200px;
}
</style>
